import { asyncRoutes, constantRoutes } from '@/router'
import { menulist } from '@/api/user'

import XEUtils from 'xe-utils'
import Layout from '@/layout'


/**
 * 导入路由组件 - webpack4支持
 * @param view
 * @returns {function(*=): any}
 * @private
 */
function _import (view) {
  return (resolve) => require([`@/views/${view}`], resolve)
}

/**
 * 导入路由组件
 * @param view
 * @returns {function(): Promise<*>}
 */
const loadView = (view) => {
  return () => import(`@/views/${view}`)
};

/**
 * 获取登录后的动态路由
 * @param roles
 */
async function getAsyncRoutesByApi() {

  let asyncRoutesArr,asyncRoutesArrMap,dataRowsMap

  return await menulist({
    funccodeName:'参数管理 系统参数 系统消息 市场参数 市场利率信息 曲线管理 基础曲线 基础曲线生成方案 直接引用 转移曲线 转移曲线设置 回收站管理 回收站'
  }).then(({data}) => {
    dataRowsMap =  XEUtils.map(JSON.parse(JSON.stringify(data.rows)), item => {
      return {
        ...item,
        parent_code:parseInt(item.parent_code),
        p_code:parseInt(item.p_code)
      }
    })
    console.log('dataRowsMapdataRowsMapdataRowsMap',dataRowsMap)


    // 数组改为路由树节点
    asyncRoutesArr = XEUtils.toArrayTree(dataRowsMap, {
      strict: true, 
      parentKey: 'parent_code', 
      key: 'p_code', 
    })
    console.log('asyncRoutesArr',asyncRoutesArr);
    // 重置路由树节点数据
    asyncRoutesArrMap = XEUtils.mapTree(asyncRoutesArr, item => {
      let component 
      if (!item.component.startsWith("Layout")) {
        component =  loadView(item.component)
      }else{
        component = Layout
      }
      return {
        path: item.path,
        component: component,
        redirect: (item.redirect === 'noRedirect')?'':item.redirect,
        name: item.name,
        hidden: item.hiden === 'true',
        // alwaysShow: (item.always_show === 'true')? true: false,
        meta: {
          title: item.meta_title,
          icon: item.meta_icon,
          noCache: item.meta_no_cache === 'true',
          affix: item.meta_affix === 'true',
          // breadcrumb: (item.meta_breadcrumb === 'true')? true: false,
        }
      }
    })


    console.log('asyncRoutesArrMapasyncRoutesArrMapasyncRoutesArrMap',asyncRoutesArrMap);
    console.log('asyncRoutesasyncRoutesasyncRoutes',asyncRoutes);
    
    return asyncRoutesArrMap

  })

}


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    console.log('constantRoutes::::::::::',constantRoutes);
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes



      /* 旧代码 */
      // if (roles.includes('admin')) {
      //   console.log('因为是超级管理员所有权限全开');
      //   // accessedRoutes = asyncRoutes || []
      //   accessedRoutes = getAsyncRoutesByApi()
      //   console.log('asyncRoutesasyncRoutesasyncRoutesasyncRoutesasyncRoutes',accessedRoutes);
      //   // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)

      // 判断是否启用后端获取路由列表做权限控制
      if (false) {
        if (roles.includes('admin')) {
          console.log('因为是超级管理员所有权限全开');
          // accessedRoutes = asyncRoutes || []
          accessedRoutes = getAsyncRoutesByApi().then((asyncRoutesArrMap) => {
            console.log('asyncRoutesasyncRoutesasyncRoutesasyncRoutesasyncRoutes',asyncRoutesArrMap);
            commit('SET_ROUTES', asyncRoutesArrMap)
            resolve(asyncRoutesArrMap)
          })
          // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
      }else{

        if (roles.includes('admin')) {
          console.log('因为是超级管理员所有权限全开');
          accessedRoutes = asyncRoutes || []
          // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)

      }

    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
